<template>
    <div class="layout">
        <ZWGroup ref="groupList" :type="11" :group-id="group_id" :auth-code="authCode" @submit="handleGroupSubmit" />
        <div class="right">
            <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" />
            <ZwTable
                ref="tableRef"
                class="table-box"
                tab-h="initial"
                :select-all-group="true"
                :option="tableOption"
                :row-key="getRowKey"
                :fetch-params="state.searchParams"
                :fetch-api="fetchApi()"
                :close-loading="true"
                @select-all="onSelectAll"
                @select="onSelect"
                @selection-change="onSelectionChange"
                @dataChange="onDataChange"
                @select-all-change="onSelectAllChange"
                @selectAllTotal="selectAllTotal">
                <template #headerOperate>
                    <el-dropdown class="dropdown_btn">
                        <el-button plain :disabled="disabled()">
                            批量操作
                            <el-icon class="el-icon--right"><arrow-down /> </el-icon>
                        </el-button>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <div v-auth="'BATCH_END'">
                                    <el-dropdown-item :disabled="disabled()" @click="batchEnds2(1)">
                                        批量结束
                                    </el-dropdown-item>
                                </div>
                                <div v-auth="'BATCH_DEL'">
                                    <el-dropdown-item :disabled="disabled()" @click="batchEnds2(2)">
                                        批量删除
                                    </el-dropdown-item>
                                </div>
                                <div v-auth="'BATCH_GROUP'">
                                    <el-dropdown-item :disabled="disabled()" @click="batchGroup(5)">
                                        批量转移分组
                                    </el-dropdown-item>
                                </div>
                                <div v-auth="'BATCH_DOW'">
                                    <el-dropdown-item :disabled="disabled()" @click="batchOpration(3)">
                                        批量下载活码
                                    </el-dropdown-item>
                                </div>
                                <div v-auth="'BATCH_DOW'">
                                    <el-dropdown-item :disabled="disabled()" @click="batchOpration(4)">
                                        批量导出数据
                                    </el-dropdown-item>
                                </div>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                    <el-button v-auth="'NEW_CODE'" type="primary" @click="newLiveCode">新建活码</el-button>
                </template>
            </ZwTable>
        </div>
        <Drawer ref="drawerRef" />
        <Dialog :app-dialog="appDialog">
            <div v-show="[1, 2].includes(batchType)" class="msg">
                <span v-if="!appDialog.inline">
                    您即将【批量{{ batchType == 1 ? '结束' : '删除' }}】<span class="msg_num">{{
                        selectTableTotal
                    }}</span>
                    条数据，确认要执行此操作吗？
                </span>
                <span v-else>{{ message }}</span>
            </div>
            <div v-show="[3, 4].includes(batchType)" class="msg">
                您即将{{ batchType == 3 ? '下载' : '导出' }}
                <span class="msg_num">
                    {{ renderNum(batchType) }}
                </span>
                条数据<span v-if="batchType == 3">（仅下载进行中的活码）</span>，确认{{
                    batchType == 3 ? '下载' : '导出'
                }}吗
            </div>
        </Dialog>
        <Dialog :app-dialog="batchGroupDialog">
            <div class="group-transfer-dialog">
                <div class="title">转移至分组：</div>
                <el-form ref="batchGroupRef" :model="batchGroupDialog" :rules="batchGroupRules" class="">
                    <el-form-item label="" prop="group_id">
                        <el-cascader
                            ref="groupCascaderRef"
                            v-model="batchGroupDialog.group_id"
                            style="width: 90%; padding-bottom: 6px"
                            :props="defaultGroup"
                            :options="groupOptions"
                            clearable
                            placeholder="请选择分组"
                            @change="groupChange"
                            @visible-change="groupVisibleChange" />
                    </el-form-item>
                </el-form>
            </div>
        </Dialog>
    </div>
</template>

<script lang="tsx">
import { defineComponent } from 'vue';
// 定义name专用script标签
// eslint-disable-next-line vue/component-definition-name-casing
export default defineComponent({ name: 'SMART_MARKETING_DRAINAGE_CHANNEL_CODE' });
</script>

<script setup lang="tsx">
import ZWGroup from '@/components/ZWGroup.vue';
import Dialog from '@/components/Dialog.vue';

import { ref, onMounted, onActivated, reactive, computed, nextTick, watch } from 'vue';
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';

import { downloadByBlob, getSetionId } from '@/utils/utils';
import { DOWLOAD_FILE } from '@/utils/smartMarketing';
import { deepCopy } from '@/utils/helper';
import { Picture as IconPicture } from '@element-plus/icons-vue';
import { ElMessage, ElImage, ElIcon, ElButton } from 'element-plus';
import {
    getCodeList,
    cusDetails,
    detailsExp,
    batchExp,
    groupTransfer
} from '@/api/smartMarketing/drainage/channelCode/index';
import { getGroupList } from '@/api/concreation';
import router from '@/router';
import bus from '@/utils/bus';
import { getCreateList } from '@/api/common';
import { endLoading, startLoading } from '@/utils/request';
import { isCachePage } from '@/utils/utils';
import Drawer from './components/Drawer.vue';

import { useRoute } from 'vue-router';
import {
    batchDownLoad,
    batchDownLoadAsync,
    batchEnd,
    asyncBatchEnd,
    batchDel,
    batchDelAsync,
    lookCode,
    beginningOrEnd,
    getChannelCodeCount
} from '@/api/smartMarketing/drainage/channelCode/index';
import { useStore } from '@/store';

import { ShowTaskMessage } from '@/hooks/TaskMessageHooks';
import { parabolaAnimation } from '@/utils/parabola';

const tableRef = ref();
const drawerRef: any = ref(null);
const groupCascaderRef = ref<any>(null);
const route = useRoute();
const group_id = ref('all');
const selectId: any = ref([]);
const batchType = ref();
const filterData = ref();
const showDrawer = ref(false);
const searchKeyWord = ref();
const list = ref([]);
const totalAll: any = ref(null);
const requestFlag = ref<boolean>(false);
const currentParams = ref<any>(null);
const filterSelect = ref<any>([]);
const downTotal = ref();
const pageData = ref({
    activity_id: '',
    page: 1,
    page_size: 15
});
const cusPage = reactive({
    page: 1,
    page_size: 15,
    total: ''
});
let clickEvent: any = null;
const store = useStore();
const tableList = ref(null);
const groupList = ref(null);
const message = ref();

const batchGroupRef = ref<any>(null);
const defaultGroup = {
    checkStrictly: true,
    emitPath: false,
    multiple: false,
    label: 'name',
    value: 'id'
};
const groupOptions = ref([]);
const batchGroupRules = reactive({
    group_id: [{ required: true, message: '请选择分组' }]
});

const searchOption = computed(() => {
    return [
        {
            label: '活码搜索',
            name: 'title',
            value: '',
            type: 'input',
            width: '280px',
            placeholder: '输入活码标题进行搜索'
        },
        {
            label: '创建人',
            name: 'user_id',
            value: [],
            multiple: true,
            type: 'select',
            filterable: true,
            placeholder: '请选择创建人',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    getCreateList({}).then((res: any) => {
                        const targetArr = res.map((item: any) => {
                            item.name = `${item.name}  (${item.phone}) `;
                            return item;
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '活码状态',
            name: 'reason',
            value: '',
            type: 'select',
            placeholder: '请选择',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    setTimeout(() => {
                        resolve([
                            { name: '全部', id: '0' },
                            { name: '进行中', id: '2' },
                            { name: '已结束', id: '3' },
                            { name: '提前结束', id: '4' }
                        ]);
                    }, 300);
                });
            },
            formatOption: (v: { name: any; id: any }) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '创建时间',
            name: 'create_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间'
        }
    ];
});
const tableOption = [
    {
        type: 'selection',
        width: 55,
        fixed: 'left',
        reserveSelection: true
    },
    {
        prop: 'activity_name',
        label: '标题',
        minWidth: 200
    },
    {
        label: '二维码',
        minWidth: 80,
        render({ row, column, index }) {
            const slotError = () => (
                <div class="image_slot">
                    <ElIcon>
                        <IconPicture />
                    </ElIcon>
                </div>
            );
            return (
                <div class="cusInfo">
                    <ElImage
                        preview-src-list={[row.qr_code_link]}
                        preview-teleported={true}
                        vSlots={{ error: slotError }}
                        src={row.qr_code_link}
                        fit="cover"
                        class="avatar"></ElImage>
                </div>
            );
        }
    },
    {
        label: '使用成员',
        width: 220,
        render({ row, column, index }) {
            return (
                <div>
                    <span vShow={row.formal.length}>
                        <span style="color: #ff6b00">{row.formal[0]}</span>等
                        <span vShow={row.formal.length}>{row.formal.length}个成员</span>
                    </span>
                </div>
            );
        }
    },
    {
        label: '备用成员',
        width: 220,
        render({ row, column, index }) {
            return (
                <div>
                    <span vShow={row.reserve.length}>
                        <span style="color: #ff6b00">{row.reserve[0]}</span>等
                        <span vShow={row.reserve.length}>{row.reserve.length}个成员</span>
                    </span>
                </div>
            );
        }
    },
    {
        prop: 'scan_num',
        label: '扫码添加次数',
        width: 200
    },
    {
        prop: 'group_name',
        label: '所属分组',
        width: 140
    },
    {
        prop: 'created_user',
        label: '创建人',
        width: 130
    },
    {
        prop: 'created_at',
        label: '创建时间',
        width: 180
    },
    {
        prop: 'status',
        label: '状态',
        width: 100,
        render({ row, column, index }) {
            return (
                <div>
                    <div vShow={row.activity_status === 1}>未开始</div>
                    <div vShow={row.activity_status === 2}>进行中</div>
                    <div vShow={row.activity_status === 3}>已结束</div>
                    <div vShow={row.activity_status === 4}>提前结束</div>
                </div>
            );
        }
    },
    {
        prop: 'operate',
        label: '操作',
        fixed: 'right',
        width: 300,
        isOperate: true,
        render({ row, column, index }) {
            return (
                <div class="handle">
                    <ElButton
                        size="small"
                        vShow={row.activity_status !== 1}
                        onClick={() => check(row)}
                        vAuth={'CUST_CODE'}>
                        客户明细
                    </ElButton>
                    <ElButton
                        size="small"
                        vShow={row.activity_status == 1 || row.activity_status == 2 || row.activity_status == 4}
                        onClick={() => look(row)}
                        vAuth={'LOOK_CODE'}>
                        查看
                    </ElButton>
                    <ElButton
                        size="small"
                        vShow={row.activity_status == 2 || row.activity_status == 1}
                        onClick={() => edit(row)}
                        vAuth={'EDIT_CODE'}>
                        编辑
                    </ElButton>
                    <ElButton
                        size="small"
                        vShow={row.activity_status == 1}
                        onClick={() => start(row)}
                        vAuth={'END_CODE'}>
                        开始
                    </ElButton>
                    <ElButton
                        size="small"
                        vShow={!row.activity_status == 4 || row.activity_status == 2}
                        onClick={() => finish(row)}
                        vAuth={'END_CODE'}>
                        结束
                    </ElButton>
                    <ElButton
                        size="small"
                        onClick={() => downloads(row)}
                        vShow={row.activity_status != 4}
                        vAuth={'DOW_CODE'}>
                        下载
                    </ElButton>
                    <ElButton
                        size="small"
                        onClick={() => goStat(row)}
                        vShow={row.activity_status != 1}
                        vAuth={'CHANNEL_STAT'}>
                        统计
                    </ElButton>
                    <ElButton size="small" onClick={() => del(row)} vAuth={'DEL_CODE'}>
                        删除
                    </ElButton>
                </div>
            );
        }
    }
];

const getRowKey = (row: any) => {
    return row.id;
};

const defaultParams = reactive({
    title: '',
    user_id: [],
    create_time: [],
    reason: '',
    group_id: 'all'
});
const state = reactive({
    searchParams: deepCopy(defaultParams)
});
const search = (data: any) => {
    selectId.value = [];
    filterSelect.value = [];

    tableRef.value.clearSelection();
    tableRef.value.clearAllSelect();
    currentParams.value = {
        ...defaultParams,
        ...data,
        ...{ group_id: group_id.value }
    };
    state.searchParams = deepCopy(currentParams.value);
};
const reset = (v?: any) => {
    cancleAllArray.value = [];
    selectId.value = [];
    filterSelect.value = [];
    currentParams.value = { ...deepCopy(defaultParams), group_id: group_id.value };
    state.searchParams = deepCopy(currentParams.value);
    tableRef.value.clearSelection();
    tableRef.value.clearAllSelect();
};
const fetchApi = () => {
    // 获取文件列表
    getTableH();
    return getCodeList;
};
// 获取表格高度
const getTableH = () => {
    nextTick(() => {
        tableRef.value.getTableH();
    });
};
const filterStatus = (type: number, selectArr: any) => {
    const res = selectArr.filter((item: any) => item.activity_status == type);
    filterSelect.value = getSetionId('id', res);
};
const renderNum = (type: any) => {
    return type == 3
        ? channelCodeCount.value || downTotal.value
        : tableRef.value.getIsSelectAll()
        ? selectTableTotal.value
        : selectId.value.length || totalAll.value;
};
// 选中表格 checkbox
const onSelect = (selection: any) => {
    filterStatus(2, selection);
    selectId.value = getSetionId('id', selection);
};
// 全选
const onSelectAll = (selection: any) => {
    filterStatus(2, selection);
    selectId.value = getSetionId('id', selection);
};
const onDataChange = (data: any) => {
    totalAll.value = data.total;
};
// 改变其选项
const onSelectionChange = (data: any) => {
    selectId.value = getSetionId('id', data);
};
// 是否禁用批量操作
const disabled = () => {
    if (selectId.value.length > 0 || selectTableTotal.value > 0) {
        return false;
    } else {
        return true;
    }
};

const selectTableTotal = ref(0);

const selectAllTotal = (value: any) => {
    selectTableTotal.value = value;
};

const cancleAllArray = ref([]);
const onSelectAllChange = (val: any) => {
    cancleAllArray.value = val;
};

const groupRef = ref();
// 分组权限code码
const authCode = {
    add: 'ADD_CHILD_CODE',
    edit: 'EDIT_GROUP_CODE',
    del: 'DEL_CHILD_GROUP'
};
// 分组信息
const handleGroupSubmit = (v: any) => {
    // 解决切换分组，点击新增然后取消之后的默认分组问题 ⬇️
    router.push({ name: 'SMART_MARKETING_DRAINAGE_CHANNEL_CODE', query: { group_id: v.id } });
    // state.searchParams.group_id = v.id
    group_id.value = v.id;
    tableRef.value.clearSelection();
    selectId.value = [];
    currentParams.value = { ...deepCopy(defaultParams), ...currentParams.value, group_id: group_id.value };
    state.searchParams = deepCopy(currentParams.value);
    tableRef.value.clearAllSelect();
    tableRef.value.clearSelection();
};
// 批量下载
const batchDwon = () => {
    let params = {
        ...state.searchParams,
        contain_ids: filterSelect.value,
        select_type: 1
    };

    if (tableRef.value.getIsSelectAll()) {
        params = {
            exclude_ids: cancleAllArray.value,
            select_type: 2,
            ...state.searchParams
        };
    }
    batchDownLoadAsync(params).then((res: any) => {
        // tableRef.value.getTable().clearSelection()
        // const type = res.name.match(/\.([^\.]+)$/)[1]
        // type == 'zip' ? DOWLOAD_FILE(res.url, res.name) : downloadByBlob(res.url, res.name)
        parabolaAnimation(clickEvent);
        ShowTaskMessage('批量下载异步任务创建成功');
        tableRef.value.clearSelection();
        tableRef.value.clearAllSelect();
    });
    cancelHandel();
};
// 批量导出数量
const batchDwonCode = () => {
    let params = {
        ...state.searchParams,
        contain_ids: selectId.value,
        select_type: 1
    };

    if (tableRef.value.getIsSelectAll()) {
        params = {
            exclude_ids: cancleAllArray.value,
            select_type: 2,
            ...state.searchParams
        };
    }

    batchExp(params).then((res: any) => {
        // tableRef.value.getTable().clearSelection()
        // DOWLOAD_FILE(res.url, res.name)
        parabolaAnimation(clickEvent);
        ShowTaskMessage('批量导出异步任务创建成功');
        tableRef.value.clearSelection();
        tableRef.value.clearAllSelect();
    });
    cancelHandel();
};
//新建活码
const newLiveCode = () => {
    bus.emit('emptyStore', {});
    router.push({
        path: '/smartMarketing/drainage/channelCode/newGroupCode',
        query: { group_id: group_id.value == 'all' ? '0' : group_id.value }
    });
};
const batchEnds2 = (type: number) => {
    batchType.value = type;
    message.value = type == 2 ? '确定是要批量删除吗？' : '结束后活码将失效，是否继续？';
    appDialog.title = type == 2 ? '批量删除' : '批量结束';
    appDialog.visible = true;
    appDialog.inline = false;
};

const channelCodeCount = ref(0);

const batchOpration = async (type: any) => {
    startLoading();
    try {
        batchType.value = type;
        let total = 0;
        if (type == 3) {
            const p = {
                ...state.searchParams,
                is_get_total: 1,
                download_status: 2
            };
            const res1 = await getCodeList(p);
            if (res1.total) {
                total = downTotal.value = res1.total;
            } else {
                total = res1.total;
            }

            let params = {
                ...state.searchParams,
                contain_ids: selectId.value,
                select_type: 1
            };
            if (tableRef.value.getIsSelectAll()) {
                params = {
                    exclude_ids: cancleAllArray.value,
                    select_type: 2,
                    ...state.searchParams
                };
            }
            const res = await getChannelCodeCount(params);
            channelCodeCount.value = res || '0';
            if (channelCodeCount.value == 0 && type == 3) {
                ElMessage.warning('您选择的活码都已结束，仅下载进行中的活码！');
                return;
            }
        }
        if (total == 0 && type == 3) {
            ElMessage.warning('暂无有效数据可下载');
            return;
        }
        appDialog.title = type == 4 ? '批量导出数据' : '批量下载活码';

        appDialog.visible = true;
    } catch (error) {
        endLoading();
    }
};

// 批量结束
const batchEnds = async () => {
    startLoading();
    try {
        let params = {
            contain_ids: selectId.value,
            select_type: 1,
            ...state.searchParams
        };
        if (tableRef.value.getIsSelectAll()) {
            params = {
                exclude_ids: cancleAllArray.value,
                select_type: 2,
                ...state.searchParams
            };
        }
        if (appDialog.inline) {
            const params = {
                activity_id: selectId.value
            };
            await batchEnd(params);
            reset();
            ElMessage.success('操作成功');
            tableRef.value.clearSelection();
            tableRef.value.clearAllSelect();
        } else {
            await asyncBatchEnd(params);
            reset();
            parabolaAnimation(clickEvent);
            ShowTaskMessage('批量结束异步任务创建成功');
            tableRef.value.clearSelection();
            tableRef.value.clearAllSelect();
        }
        cancelHandel();
    } catch (error) {
        endLoading();
    }
};
// 批量删除
const batchDels = async () => {
    startLoading();
    try {
        // batchType.value = 2
        let params = {
            contain_ids: selectId.value,
            select_type: 1,
            ...state.searchParams
        };
        if (tableRef.value.getIsSelectAll()) {
            params = {
                exclude_ids: cancleAllArray.value,
                select_type: 2,
                ...state.searchParams
            };
        }
        if (appDialog.inline) {
            params = {
                activity_id: selectId.value
            };
            await batchDel(params);
            reset();
            ElMessage.success('删除成功');
            refreshGroup();
            appDialog.inline = false;
            tableRef.value.clearSelection();
            tableRef.value.clearAllSelect();
        } else {
            await batchDelAsync(params);
            reset();
            refreshGroup();
            parabolaAnimation(clickEvent);
            ShowTaskMessage('批量删除异步任务创建成功');
            tableRef.value.clearSelection();
            tableRef.value.clearAllSelect();
        }
        cancelHandel();
    } catch (error) {
        endLoading();
    }
};
// 批量转移分组
const batchGroup = val => {
    batchGroupDialog.group_id = '';
    batchGroupDialog.visible = true;
};

/**
 * 选择分组
 */
const groupChange = () => {
    groupCascaderRef.value.togglePopperVisible();
};

/**
 * 获取分组数据
 * @param val
 */
const groupVisibleChange = async (val: boolean) => {
    if (val) {
        const res = await getGroupList({ type: 11 });
        groupOptions.value = res.data;
    }
};
const getDelList = (data: any) => {
    cusDetails(data).then((res: any) => {
        filterData.value = res.list || res.data;
        showDrawer.value = true;
        cusPage.total = res.total;
    });
};
// 客户明细
const check = (data: any) => {
    drawerRef.value.openFn(data.id);
};

const exportDetils = () => {
    detailsExp(pageData.value).then((res: any) => {
        window.location.href = res.url;
    });
};
// 查看
const look = (data: any) => {
    router.push({
        path: '/smartMarketing/drainage/channelCode/newGroupCode',
        query: { type: 'look', id: data.id }
    });
};

const toDetail = (row: any) => {
    const { cust_id: id, cust_type: type } = row;
    const url = `/customer/manage/list/detail?id=${id}&type=${type}`;
    window.open(url, '_blank');
};
//编辑
const edit = (data: any) => {
    // isEdit.value = true
    router.push({
        path: '/smartMarketing/drainage/channelCode/newGroupCode',
        query: { type: 'edit', id: data.id }
    });
};
// 开始
const start = (data: any) => {
    const result = { activity_id: data.id, status: 1 };
    beginningOrEnd(result)
        .then((res: any) => {
            // getList(params)
            reset();
            tableRef.value.clearSelection();
            tableRef.value.clearAllSelect();
        })
        .catch((e: any) => {});
};
// 结束
const finish = (data: any) => {
    batchType.value = 1;
    selectId.value = [data.id];
    message.value = '结束活码不可再次扫码添加';
    appDialog.title = '结束';
    appDialog.visible = true;
    appDialog.inline = true;
};

// 删除
const del = (data: any) => {
    appDialog.inline = true;
    batchType.value = 2;
    selectId.value = [data.id];
    message.value = '确认要删除吗？';
    appDialog.title = '删除';
    appDialog.visible = true;
};
// 下载
const downloads = (data: any) => {
    const params = {
        group_id: group_id.value,
        activity_ids: []
    };
    params.activity_ids.push(data.id);
    batchDownLoad(params).then((res: any) => {
        const type = res.name.match(/\.([^\.]+)$/)[1];
        type == 'zip' ? DOWLOAD_FILE(res.url, res.name) : downloadByBlob(res.url, res.name);
        // tableRef.value.clearSelection();
        // tableRef.value.clearAllSelect();
    });
};
// 统计
const goStat = (row: any) => {
    router.push({
        path: '/smartMarketing/drainage/channelCode/stat',
        query: { id: row.id, group_id: group_id.value }
    });
};

const refreshGroup = async () => {
    await groupList.value.getGroup(11);
};
const cancelHandel = () => {
    // 弹窗取消时文案显示不正确wh
    batchType.value = '';
    appDialog.visible = false;
};
const submitHandel = e => {
    clickEvent = e;
    switch (batchType.value) {
        case 1:
            batchEnds();
            break;
        case 2:
            batchDels();
            break;
        case 3:
            batchDwon();
            break;
        case 4:
            batchDwonCode();
            break;
    }
};
// 弹框配置项
const appDialog = reactive({
    visible: false,
    title: '批量结束',
    width: '400px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '确定',
    isInit: false, //是否重置
    isChooseDisabled: false, //重新打开传递进来的数据是否重置
    chooseArr: [], // 传递进来选中的数据
    inline: false // 是否行内操作
});

const groupCancelHandel = () => {
    batchGroupDialog.visible = false;
};

/**
 * 分组弹框确认事件
 */
const groupSubmitHandel = async () => {
    await batchGroupRef.value?.validate();
    const select_type = tableRef.value.getIsSelectAll() ? 2 : 1;
    const params = {
        ...state.searchParams,
        exclude_ids: select_type == 2 ? cancleAllArray.value : [],
        contain_ids: select_type == 1 ? selectId.value : [],
        select_type: select_type,
        transfer_group_id: batchGroupDialog.group_id
    };
    const res = await groupTransfer(params);
    batchGroupDialog.visible = false;
    tableRef.value.clearSelection();
    tableRef.value.clearAllSelect();
    ElMessage.success('转移成功');
    tableRef.value.reload();
    groupList.value.getGroup();
};

// 批量转移分组弹框配置项
const batchGroupDialog = reactive({
    group_id: '',
    visible: false,
    title: '批量转移分组',
    width: '500px',
    cancel: groupCancelHandel,
    submit: groupSubmitHandel,
    cancelText: '取消',
    submitText: '确定'
});
watch(
    () => searchKeyWord.value,
    () => {
        filterData.value = list.value.filter((item: any) => {
            // store.dispatch("pageTotal", filterData.value.total);
            return item.created_user.indexOf(searchKeyWord.value) != -1;
        });
    }
);
onMounted(async () => {
    // store.dispatch('content/changeType', 11)
    const groupId = Number(route.params?.group_id || route.query?.group_id);
    if (groupId) {
        group_id.value = groupId;
        await groupList.value.setCurrentSelectId({ id: groupId });
    }
});
onActivated(async (val: any) => {
    const groupId = Number(route.params?.group_id || route.query?.group_id);
    if (isCachePage() || groupId || groupId == 0) {
        if ((groupId || groupId == 0) && group_id.value != groupId) {
            group_id.value = groupId;
        } else {
            await groupList.value.getGroup(11);
        }
        tableRef.value.clearSelection();
        tableRef.value.clearAllSelect();
        groupList.value.setCurrentSelectId({ id: group_id.value });
        state.searchParams = {
            ...deepCopy(defaultParams),
            ...currentParams.value,
            group_id: groupId || group_id.value
        };
    }
});
</script>

<style lang="scss" scoped>
.layout {
    display: flex;

    .right {
        flex: 1;
        height: calc(100vh - 142px);
        padding: 24px;
        overflow: hidden;
        box-sizing: border-box;
        background: #fff;
        border: 1px solid #eaeaea;
        display: flex;
        flex-direction: column;

        .zw-table {
            display: flex;
            flex-direction: column;
            flex: 1;
            overflow: hidden;

            :deep(.el-table) {
                flex: 1;

                .el-table__empty-block {
                    position: absolute;
                    top: 50%;
                    left: 50%;
                    transform: translate(-50%, -50%);
                }
            }
        }

        :deep(.cusInfo) {
            display: flex;
            align-items: center;

            .cust_border {
                margin: 0 5px;
            }

            .cust_nickname {
                max-width: 70px;
                text-overflow: ellipsis;
                overflow: hidden;
                white-space: nowrap;
                margin-right: 5px;
            }

            .cust_remark {
                &_text {
                    max-width: 150px;
                    text-overflow: ellipsis;
                    overflow: hidden;
                    white-space: nowrap;
                }
            }

            .avatar {
                width: 60px;
                height: 60px;
                border-radius: 4px;

                .image-slot {
                    .el-icon {
                        font-size: 36px;
                    }
                }
            }

            .name {
                margin: 0 5px;
            }

            .channel {
                font-size: 14px;
                color: #60b900;
            }

            .sex {
                width: 18px;
                height: 18px;

                img {
                    width: 100%;
                    height: 100%;
                }
            }
        }
    }
}

.msg {
    text-align: center;
    padding: 50px 0;

    &_num {
        color: #ff6b00;
    }
}

.tableData {
    background: #fff;

    // box-sizing: border-box;
    border: 1px solid #eaeaea;

    .cusInfo {
        display: flex;
        align-items: center;

        &:hover {
            cursor: pointer;
            color: #2fb6e4;
        }

        .cusConet {
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
            width: 150px;
            margin-left: 8px;
        }

        .cust_border {
            margin: 0 5px;
        }

        .cust_nickname {
            max-width: 70px;
            text-overflow: ellipsis;
            overflow: hidden;
            white-space: nowrap;
            margin-right: 5px;
        }

        .cust_remark {
            display: flex;
            align-items: center;

            &_text {
                max-width: 150px;
                text-overflow: ellipsis;
                overflow: hidden;
                white-space: nowrap;
            }
        }

        .avatar {
            width: 60px;
            height: 60px;
            border-radius: 4px;

            .image-slot {
                .el-icon {
                    font-size: 36px;
                }
            }
        }

        .name {
            margin: 0 5px;
        }

        .channel {
            font-size: 14px;
            color: #60b900;
        }

        .sex {
            width: 18px;
            height: 18px;

            img {
                width: 100%;
                height: 100%;
            }
        }
    }

    .tagList {
        display: flex;
        align-items: center;
        flex-wrap: wrap;

        .tag_item {
            padding: 4px;
            color: #ff6b00;
            margin: 0 10px 10px 0;
            border-radius: 2px;
            border: 1px solid #ffc69e;

            &:nth-child(n + 6) {
                display: none;
            }
        }
    }

    .emty {
        margin-top: 200px;

        // display: flex;
        // flex-direction: column;
    }

    .emty_img {
        transform: translateX(15%);
    }

    .emty_title {
        margin-top: -50px;
    }
}

.emty_img {
    transform: translateX(15%);
}

.drawerTitle {
    font-family: PingFangSC-Medium, 'PingFang SC';
    font-weight: 500;
    color: #33302d;
}

.export_btn {
    text-align: right;

    .btn {
        margin-bottom: 16px;
    }
}

.cust_remark {
    &_text {
        display: inline-block;
        max-width: 50px;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
    }
}

.export_btn {
    text-align: right;

    .btn {
        margin-bottom: 16px;
    }
}

.dropdown_btn {
    margin-right: 10px;
}

.group-transfer-dialog {
    .title {
        padding: 10px 0 15px;

        &::before {
            content: '*';
            color: var(--el-color-danger);
            margin-right: 4px;
        }
    }
}
</style>
